﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Logic.Enums;
using Twitterizer;
using System.Configuration;
using BLL;
using Facebook;

namespace BO
{
    public partial class Account : BLL.EntityBase
    {
        public AccountType Type
        {
            get
            {
                return !string.IsNullOrEmpty(this.TwKey) ? AccountType.Twitter : AccountType.Facebook;
            }
        }
    }

    public partial class Post : BLL.EntityBase
    {
        public String Icon
        {
            get
            {
                return this.Sentiment > 0 ? "happy" : "sad";
            }
        }

        public void Reply(string res)
        {
            if (this.Type == (int)AccountType.Twitter)
                ReplyTwitter(res);
            else ReplyFacebook(res);
        }
        // post with account
        private void ReplyTwitter(string res)
        {
            if (this.Account == null)
                this.Account = BLL.Accounts.GetByID(this.AccountID);

            TwitterStatus.Update(GetTokens(this.Account), string.Format("@{0} {1}"
                                                                        , this.FromUserName
                                                                        , res)
                                , new StatusUpdateOptions { InReplyToStatusId = Convert.ToDecimal(this.ForeignID) });
        }

        public OAuthTokens GetTokens(Account a)
        {
            return new OAuthTokens
            {
                AccessToken = a.TwKey,
                AccessTokenSecret = a.TwSecret,

                ConsumerKey = ConfigurationManager.AppSettings["TwitterToken"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwitterTokenSecret"]
            };
        }

        private void ReplyFacebook(string res)
        {
            if (this.FBPage == null)
                this.FBPage = BLL.FBPages.GetByID(this.PageID);

            FacebookClient fbClient = new FacebookClient(this.FBPage.Token);
            fbClient.Post(string.Format("{0}/comments", this.ForeignID), new { message = res });
        }
    }
}
